<?php
/**
 * Zead
 *
 * LICENSE	
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.opensource.org/licenses/bsd-license.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to eu@marcelomx.com so we can send you a copy immediately.
 *
 * @category   Zead
 * @author     Marcelo Rodrigues Gonzaga <eu@marcelomx.com>
 * @copyright  Copyright (c) 2008 Marcelo Rodrigues Gonzaga
 * @link       http://code.google.com/p/zead 
 * @license    http://www.opensource.org/licenses/bsd-license.php     New BSD License
 *
 **/


/** @see Zead_Xml_Exception **/
require_once 'Zead/Xml/Exception.php';

/** @see Zead_Xml_Element **/
require_once 'Zead/Xml/Element.php';

/**
 * Abstract class Zead_Xml_Abstract
 *
 * @category   Zead
 * @package    Zead_Xml
 * @copyright  Copyright (c) 2008 Marcelo Rodrigues Gonzaga 
 * @license    http://www.opensource.org/licenses/bsd-license.php     New BSD License 
 */
abstract class Zead_Xml_Abstract extends DOMDocument
{
	/**
 	 * Class constructor
	 * @param string $version   A versão do XML
	 * @param string $encoding  O encoding
	 */
	public function __construct($version = '1.0', $encoding = 'utf8')
	{
		// Registrando as classes DOM customizadas
		if (get_class($this) == 'Zead_Xml_Abstract') {
			throw new Zead_Xml_Exception('The class base need to be a extended class of Zead_Xml_Abstract');
		}	
		parent::__construct($version, $encoding);
		
		$this->registerNodeClass('DOMDocument', get_class($this));
		$this->registerNodeClass('DOMElement', 'Zead_Xml_Element');
	}

	/**
	 * Import the default nodes from array
	 * @param array $data
	 */
	public function fromArray(array $array = array()) 
	{			
		if (!sizeof($array))
			return;

		$array = new ArrayIterator($array);

		if (!$this->documentElement)
			$this->appendChild($this->createElement($array->key()));
		
		// Set attributes
		$this->documentElement->fromArray((array) $array);
	}
	
	/**
	 * Transforma o documento XML em um ARRAY
	 * @return array
	 */
	public function toArray() 
	{
		if (!$this->documentElement)
			return array();
		
		return $this->documentElement->toArray();
	}
}

